package com.kl.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kl.domain.DetailedDTO;
import com.kl.domain.WaybillDTO;
import com.kl.em.ConstantEnum;
import com.kl.em.Result;

import com.kl.entity.Waybill;
import com.kl.feign.CollectionServiceFeign;
import com.kl.feign.CreatOrderServiceFeign;
import com.kl.feign.FreightServiceFeign;
import com.kl.mapper.TabOrderMapper;
import com.kl.mapper.WaybillMapper;
import com.kl.service.IWaybillService;
import com.mongodb.client.result.UpdateResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2021-10-30
 */
@RestController
@RequestMapping("/waybill")
public class WaybillController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private FreightServiceFeign freightServiceFeign;

    @Autowired
    private IWaybillService iWaybillService;

    @Autowired
    private TabOrderMapper orderMapper;

    @Autowired
    private WaybillMapper waybillMapper;

    @Autowired
    private CreatOrderServiceFeign detailedServiceFeign;

    @Autowired
    private CollectionServiceFeign collectionServiceFeign;


    @ApiOperation(value = "运单表状态模糊查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "运单表运单状态", required = true,
                    paramType = "path", dataTypeClass = String.class)
    })
    @GetMapping("/likeWaybill/{status}")
    public Result<List<WaybillDTO>> likeWaybill(@PathVariable("status") String status){
//        Result all = freightServiceFeign.getPrice(1,1,1);
        System.out.println(status);
        List<Waybill> waybills = iWaybillService.likeWaybill(status);
        String s = JSONObject.toJSONString(waybills);

        List<WaybillDTO> waybillDTOS = JSONObject.parseArray(s, WaybillDTO.class);
        return Result.build(ConstantEnum.SUCCESS).setResult(waybillDTOS);
    }

    @ApiOperation(value = "运单表增加接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "waybillDTO", value = "运单表实体类", required = true,
                    paramType = "body", dataTypeClass = WaybillDTO.class)
    })
    @PostMapping("/addWaybill")
    public Result addWaybill(@RequestBody WaybillDTO waybillDTO){

        String id = RandomStringUtils.randomNumeric(16);
        waybillDTO.setWaybillId(Long.parseLong(id));
        Waybill waybill = new Waybill();
        BeanUtils.copyProperties(waybillDTO,waybill);
        try {
            Result result = iWaybillService.addWaybill(waybill);
            mongoTemplate.save(waybillDTO);
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.build(ConstantEnum.SUCCESS);
    }

    @ApiOperation(value = "运单表修改接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "waybillDTO", value = "运单表实体类", required = true,
                    paramType = "body", dataTypeClass = WaybillDTO.class)
    })
    @PutMapping("/updateWaybill")
    public Result updateWaybill(@RequestBody WaybillDTO waybillDTO){

        Query query = new Query(Criteria.where("waybillId").is(waybillDTO.getWaybillId()));
//        Update update = new Update().set("logisticsStatus", logisticsStatus)
//                .set("currentSite", currentSite).set("nextLine", nextLine);

        Update update = new Update().set("cargoName", waybillDTO.getCargoName())
                .set("logisticsStatus",waybillDTO.getLogisticsStatus())
                .set("changeTime",new Date())
                .set("currentSite",waybillDTO.getCurrentSite())
                .set("warehouseEntryTime",waybillDTO.getWarehouseEntryTime())
                .set("zhuangche",waybillDTO.getZhuangche())
                .set("nextLine",waybillDTO.getNextLine());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, WaybillDTO.class);

        if(Integer.parseInt(waybillDTO.getLogisticsStatus()) >= 5 || Integer.parseInt(waybillDTO.getLogisticsStatus()) == 0){
            Query query1 = new Query();
            query1.addCriteria(Criteria.where("waybillId").is(waybillDTO.getWaybillId()));
//        Waybill waybill = mongoTemplate.findOne(query, Waybill.class,"waybillList");
            List<WaybillDTO> waybills = mongoTemplate.find(query1, WaybillDTO.class);
            if(waybills.size() <= 0){
                waybills = null;
                return Result.build(ConstantEnum.ERROR).setResult(waybills);
            }
            Waybill waybill = new Waybill();
            BeanUtils.copyProperties(waybills.get(0),waybill);
            boolean b = iWaybillService.updateById(waybill);
            // Result result = iWaybillService.updateWaybill(waybills.get(0));
           // return result;
        }
        return Result.build(ConstantEnum.SUCCESS).setResult(1);
    }

    //发货收货, 状态(0,已撤销;1,待揽件;2,已揽件;3,运输中;4,待派送;5,到终点站;6,已损坏;7,已丢失,8已签收)',可以通过这个方法修改
    @ApiOperation(value = "运单表更新信息和运单状态接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "waybillId", value = "运单id", required = true,
                    paramType = "query"),
            @ApiImplicitParam(name = "information", value = "运单表更新信息", required = true,
                    paramType = "query")
    })
    @PutMapping("/updateUpdateInformation")
    public Result updateUpdateInformation(@RequestParam Long waybillId,@RequestParam String information,@RequestParam String status){
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("waybillId").is(waybillId));
        List<WaybillDTO> waybills = mongoTemplate.find(query1, WaybillDTO.class);
        if(waybills.size() <= 0){
            return Result.build(ConstantEnum.ERROR);
        }
        String s = waybills.get(0).getUpdateInformation();
        List<String> updateInformationList = JSONObject.parseArray(s,String.class);

        if(updateInformationList == null){
            updateInformationList = new ArrayList<String>();
        }



        Query query = new Query(Criteria.where("waybillId").is(waybillId));
        Update update = null;
       if(information.equals("") || information == null){
          update = new Update().set("logisticsStatus",status);
       }else{
           updateInformationList.add(information);
           String updateInformation = JSONObject.toJSONString(updateInformationList);
           update = new Update().set("updateInformation", updateInformation).set("logisticsStatus",status);
       }

        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, WaybillDTO.class);

        return Result.build(ConstantEnum.SUCCESS).setResult(updateResult);
    }



    @ApiOperation(value = "运单表查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "waybillId", value = "运单表id", required = true,
                    paramType = "path", dataTypeClass = Long.class)
    })
    @GetMapping("/findWaybill/{waybillId}")
    public Result<WaybillDTO> findWaybill(@PathVariable("waybillId") Long waybillId){

        Query query = new Query();
        query.addCriteria(Criteria.where("waybillId").is(waybillId));
//        Waybill waybill = mongoTemplate.findOne(query, Waybill.class,"waybillList");
        List<WaybillDTO> waybills = mongoTemplate.find(query, WaybillDTO.class);

        if(waybills.size() <= 0){
           waybills = null;
            return Result.build(ConstantEnum.SUCCESS).setResult(waybills);
        }
//        Waybill waybill = mongoTemplate.findById(waybillId, Waybill.class);
//        WaybillDTO waybillDTO = new WaybillDTO();
//        BeanUtils.copyProperties(waybills.get(0),waybillDTO);
        return Result.build(ConstantEnum.SUCCESS).setResult(waybills.get(0));
    }


    @ApiOperation(value = "电话号码查询运单表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "consigneePhone", value = "收货人电话", required = true,
                    paramType = "path", dataTypeClass = String.class)
    })
    @GetMapping("/findWaybillByPhone/{consigneePhone}")
    public Result<List<WaybillDTO>> findWaybillByPhone(@PathVariable("consigneePhone") String consigneePhone){

        Query query = new Query();
        query.addCriteria(Criteria.where("consigneePhone").is(consigneePhone));
//        Waybill waybill = mongoTemplate.findOne(query, Waybill.class,"waybillList");
        List<Waybill> waybills = mongoTemplate.find(query, Waybill.class);

        if(waybills.size() <= 0){
            waybills = null;
            return Result.build(ConstantEnum.SUCCESS).setResult(waybills);
        }
//        Waybill waybill = mongoTemplate.findById(waybillId, Waybill.class);
        String s = JSONObject.toJSONString(waybills);
        List<WaybillDTO> waybillDTOS = JSONObject.parseArray(s, WaybillDTO.class);

        return Result.build(ConstantEnum.SUCCESS).setResult(waybillDTOS);
    }




    @ApiOperation(value = "运单表删除接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "waybillId", value = "运单表id", required = true,
                    paramType = "path", dataTypeClass = Long.class)
    })
    @DeleteMapping("/deleteWaybill/{waybillId}")
    public Result deleteWaybill(@PathVariable("waybillId") Long waybillId){
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("waybillId").is(waybillId));
//        Waybill waybill = mongoTemplate.findOne(query, Waybill.class,"waybillList");
        List<Waybill> waybills = mongoTemplate.find(query1, Waybill.class);
        Query query = new Query(Criteria.where("waybillId").is(waybillId));
        Update update = new Update();
        update.pull("Waybill",waybills.get(0));
        mongoTemplate.updateFirst(query,update,"class");
        Result result = iWaybillService.deleteWaybill(waybillId);
        return result;
    }

    @ApiOperation(value = "通过订单id查询运单id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单表id", required = true,
                    paramType = "path", dataTypeClass = Long.class)
    })
    @GetMapping("/findWaybillByOrderId/{orderId}")
    public Result<List<WaybillDTO>> findWaybillByOrderId(@PathVariable("waybillId") Long orderId){

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("order_id",orderId);
        List<WaybillDTO> list = orderMapper.selectList(wrapper);
        String s = JSON.toJSONString(list);
        List<WaybillDTO> waybillDTOList = JSONObject.parseArray(s, WaybillDTO.class);


        return Result.build(ConstantEnum.SUCCESS).setResult(waybillDTOList);
    }


    @ApiOperation(value = "通过运单id修改运单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "waybillId", value = "运单表id", required = true,
                    paramType = "query", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "logisticsStatus", value = "运单状态", required = true,
                    paramType = "query", dataTypeClass = String.class)
    })
    @PutMapping
    public Result updateById(@RequestParam Long waybillId,@RequestParam String logisticsStatus){
        Waybill waybill = new Waybill();
        waybill.setWaybillId(waybillId);
        waybill.setLogisticsStatus(logisticsStatus);
        boolean b = waybill.updateById();
        if (b){
            if (logisticsStatus.equals("5")){
                List<DetailedDTO> list = detailedServiceFeign.findDetailById(waybillId).getResult();
                if (list != null && list.size() != 0){
                    BigDecimal totalPrice = list.get(0).getTotalPrice();
                    long l = totalPrice.longValue();
                    if (l > 0){
                        //调用代收货款insert//1
                        collectionServiceFeign.insertCollection(waybillId.toString(),"1");
                    }
                }
            }
            if (logisticsStatus.equals("6") || logisticsStatus.equals("7")){

                collectionServiceFeign.insertCollection(waybillId.toString(),"2");

            }
            return Result.build(ConstantEnum.SUCCESS);
        }else {
            return Result.build(ConstantEnum.ERROR);
        }
    }

    //ByID
    @GetMapping("/selectById")
    public Result<WaybillDTO> selectById(@RequestParam Long waybillId){

        Waybill waybill = waybillMapper.selectById(waybillId);
        WaybillDTO waybillDTO = new WaybillDTO();
        BeanUtils.copyProperties(waybill,waybillDTO);

        return Result.build(ConstantEnum.SUCCESS).setResult(waybillDTO);
    }


    @ApiOperation(value = "通过运单是否装车查询运单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "zhuangche", value = "运单表id", required = true,
                    paramType = "query", dataTypeClass = Integer.class)
    })
    @GetMapping("/selectByZhuang")
    public Result<List<WaybillDTO>> selectByZhuang(@RequestParam Integer zhuangche){
        QueryWrapper<Waybill> queryWrapper = new QueryWrapper();
        queryWrapper.eq("zhuangche",zhuangche);

        List<Waybill> waybills = waybillMapper.selectList(queryWrapper);
        String s = JSONObject.toJSONString(waybills);
        List<WaybillDTO> waybillDTOS = JSONObject.parseArray(s, WaybillDTO.class);

        return Result.build(ConstantEnum.SUCCESS).setResult(waybillDTOS);
    }


}
